$(document).ready(function(){
	
	$('input:checkbox').click(function(){
		$(this).parent().parent().toggleClass('ui-state-highlight');
	});

	// Uploadify's options
	$('#company-file-upload').uploadify({
		'uploader'  : 'inc/uploadify.swf',
		'script'    : 'process/upload_docs.php',
		'cancelImg' : 'css/img/cancel.png',
		'buttonImg'	: 'css/img/folder_add.png',
		'folder'    : 'data/docs',
		'auto'      : false,
		'multi'		: true,
		'wmode'		: 'transparent',
		'height'	: '16',
		'scriptData': { 'otype':'company', 'id':$('input[name=company-companyId]').val() },
		'onAllComplete'	: function(event,data){
			location.reload();
		}
	});
	
	// Case: deleting a company's document
	$('a.delete-doc').click(function(){
		var e = $(this);
		$.ajax({
			type:	'POST',
			url:	'process/document_delete.php',
			data:	'id='+e.attr('href'),
			success: function(msg){
				if (msg != 'OK')
					alert(msg);
				else
					e.parent().parent().remove();
			}
		});
		return false;
	});

	// Case: seeing a company's details
	$('a#details').click(function(){
		
		// Checking if we have an activity selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner un élément !');
			return false;
		}
		
		// Redirecting user to the company
		$(this).attr('href', 'companies.php?id='+checked.first().val()+'&operation=edit');
		return true;
	});
	
	// Case: deleting a company batch
	$('a#delete').click(function(){
		
		// Checking rights
		if (check_credentials('company_delete') != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking if we have at least one company selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// AJAXing deletion
		if (confirm('Êtes-vous sûr de vouloir supprimer '+checked.length+' élément(s) ?')) {
			var total = checked.length;
			showLoading();
			checked.each(function(){
				$.ajax({
					type:	'POST',
					url:	'process/company_delete.php',
					data:	'id='+$(this).val(),
					success: function(msg){
						if (msg != 'OK')
							alert(msg);
						else
							checked.parent().parent().remove();
						addLoading(100/total);
						closeLoading();
					}
				});
			});
		}
		return false;
	});
	
	// Case: editing company's main contact
	$('input[name=company-contact]').click(function(){
		var e = $(this);
		e.addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/load_contacts.php',
			data:	'id='+$('input[name=company-contactId]').val(),
			success: function(msg) {
				var select = $('div#select_contact');
				e.removeClass('loading');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var checked = $('input:radio:checked');
							if (checked.length <= 0) {
								$('input[name=company-contact]').val('');
								$('input[name=company-contactId]').val('');
							} else {
								$('input[name=company-contact]').val($('span#contact-'+checked.first().val()).html());
								$('input[name=company-contactId]').val(checked.first().val());
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
	
	// Case: editing company's activitysector
	$('input[name=company-activitysector]').click(function(){
		var e = $(this);
		e.addClass('loading');
		$.ajax({
			type:	'POST',
			url:	'ajax/load_sectors.php',
			data:	'id='+$('input[name=company-activitysectorId]').val(),
			success: function(msg) {
				var select = $('div#select_sector');
				e.removeClass('loading');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var checked = $('input:radio:checked');
							if (checked.length <= 0) {
								$('input[name=company-activitysector]').val('');
								$('input[name=company-activitysectorId]').val('');
							} else {
								$('input[name=company-activitysector]').val($('span#sector-'+checked.first().val()).html());
								$('input[name=company-activitysectorId]').val(checked.first().val());
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
	});
	
	// Case: submitting a new (or edited) company
	$('a#form-company').click(function(){
		
		// Getting inputs
		var operation = $('input[name=company-operation]'),
			id = $('input[name=company-companyId]'),
			name = $('input[name=company-name]'),
			contact = $('input[name=company-contactId]'),
			activitysector = $('input[name=company-activitysectorId]'),
			ad_name = $('input[name=address-name]'),
			ad_building = $('input[name=address-building]'),
			ad_number = $('input[name=address-number]'),
			ad_street = $('input[name=address-street]'),
			ad_city = $('input[name=address-city]'),
			ad_postalcode = $('input[name=address-postalcode]'),
			allFields = $([]).add(name).add(ad_number).add(ad_street).add(ad_city).add(ad_postalcode);
		
		// Checking rights
		if (check_credentials('company_'+operation.val()) != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking form validity
		allFields.removeClass('ui-state-error');
		var valid = true;
		valid = valid && check_length(name, 'Nom', 1, 255);
		valid = valid && check_length(ad_number, 'Numéro', 1, 10);
		valid = valid && check_length(ad_street, 'Rue', 1, 255);
		valid = valid && check_length(ad_city, 'Ville', 1, 255);
		valid = valid && check_length(ad_postalcode, 'Code Postal', 5, 5);
		valid = valid && check_regexp(ad_postalcode, rexp_postal, 'Merci d\'indiquer un code postal français');
		
		// We have errors
		if (!valid)
			return false;

		// No error: AJAX processing
		showLoading();
		$.ajax({
			type:	'POST',
			url:	'process/company_'+operation.val()+'.php',
			data:	'id='+id.val()+'&name='+name.val()+'&contact='+contact.val()+'&activitysector='+activitysector.val()+'&ad_name='+ad_name.val()+'&ad_building='+ad_building.val()+'&ad_number='+ad_number.val()+'&ad_street='+ad_street.val()+'&ad_city='+ad_city.val()+'&ad_postalcode='+ad_postalcode.val(),
			success: function(msg){
				addLoading(100);
				history.back();
			}
		});
		return false;
	});
	
	// Case: seeing a prorole's details
	$('a#details-prorole').click(function(){
		
		// Checking if we have a prorole selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner un élément !');
			return false;
		}
		
		// Redirecting user to the prorole
		$(this).attr('href', 'gotproroles.php?id='+checked.first().val()+'&operation=edit');
		return true;
	});
	
	// Case: deleting a prorole batch
	$('a#delete-prorole').click(function(){
		
		// Checking rights
		if (check_credentials('gotprorole_delete') != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking if we have at least one prorole selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// AJAXing deletion
		if (confirm('Êtes-vous sûr de vouloir supprimer '+checked.length+' élément(s) ?')) {
			var total = checked.length;
			showLoading;
			checked.each(function(){
				$.ajax({
					type:	'POST',
					url:	'process/gotprorole_delete.php',
					data:	'id='+$(this).val(),
					success: function(msg){
						if (msg != 'OK')
							alert(msg);
						else
							checked.parent().parent().remove();
						addLoading(100/total);
						closeLoading();
					}
				});
			});
		}
		return false;
	});
	
	// Case: seeing a studentactivity's details
	$('a#details-studentactivity').click(function(){
		
		// Checking if we have a studentactivity selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner un élément !');
			return false;
		}
		
		// Redirecting user to the studentactivity
		$(this).attr('href', 'gotstudentactivities.php?id='+checked.first().val()+'&operation=edit');
		return true;
	});
	
	// Case: deleting a studentactivity batch
	$('a#delete-studentactivity').click(function(){
		
		// Checking rights
		if (check_credentials('gotstudentactivity_delete') != 'yes'){
			alert('Vous n\'avez pas le droit d\'effectuer cette opération !');
			return false;
		}
		
		// Checking if we have at least one studentactivity selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// AJAXing deletion
		if (confirm('Êtes-vous sûr de vouloir supprimer '+checked.length+' élément(s) ?')) {
			var total = checked.length;
			showLoading();
			checked.each(function(){
				$.ajax({
					type:	'POST',
					url:	'process/gotstudentactivity_delete.php',
					data:	'id='+$(this).val(),
					success: function(msg){
						if (msg != 'OK')
							alert(msg);
						else
							checked.parent().parent().remove();
						addLoading(100/total);
						closeLoading();
					}
				});
			});
		}
		return false;
	});
	
	// Case: merging company
	$('a#merge').click(function(){
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// Merging each company
		$.ajax({
			type:	'POST',
			url:	'ajax/load_models.php',
			success: function(msg) {
				var select = $('div#select_model');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var model = $('input:radio:checked');
							if (model.length > 0) {
								checked.each(function(){
									window.open('process/company_merge.php?model='+model.first().val()+'&company='+$(this).val());
								});
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
		return false;
	});
	
	// Case: merging company's gotprorole
	$('a#merge-prorole').click(function(){
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// Merging each gotprorole
		$.ajax({
			type:	'POST',
			url:	'ajax/load_models.php',
			success: function(msg) {
				var select = $('div#select_model');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var model = $('input:radio:checked');
							if (model.length > 0) {
								checked.each(function(){
									window.open('process/gotprorole_merge.php?model='+model.first().val()+'&gotprorole='+$(this).val());
								});
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
		return false;
	});
	
	// Case: merging company's studentactivity
	$('a#merge-studentactivity').click(function(){
		
		// Checking if we have at least one contact selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// Merging each studentactivity
		$.ajax({
			type:	'POST',
			url:	'ajax/load_models.php',
			success: function(msg) {
				var select = $('div#select_model');
				select.html(msg);
				select.dialog({
					resizable: true,
					height: 500,
					width: 500,
					modal: true,
					buttons: {
						'Sélectionner': function(){
							var model = $('input:radio:checked');
							if (model.length > 0) {
								checked.each(function(){
									window.open('process/gotstudentactivity_merge.php?model='+model.first().val()+'&gotstudentactivity='+$(this).val());
								});
							}
							$(this).dialog('close');
						},
						'Annuler': function(){
							$(this).dialog('close');
						}
					}
				});
			}
		});
		return false;
	});
	
	// Case: e-mailing company
	$('a#sendmail').click(function(){

		// Checking if we have at least one company selected
		var checked = $('input:checkbox:checked');
		if (checked.length <= 0) {
			alert('Vous devez sélectionner au moins un élément !');
			return false;
		}
		
		// Retreiving company's contact's e-mail
		$.ajax({
			type:	'POST',
			url:	'ajax/get_contact_email.php',
			data:	'id='+checked.first().val(),
			success: function(msg){
				if (msg.length > 0)
					window.open('mailto:'+msg);
				else
					alert('Cette société ne dispose pas d\'un contact principal ou ce dernier n\'a pas d\'e-mail !');
			}
		});
		return false;
	});
});